package com.guokai2012.util;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @ClassName MyJFrame
 * @Author guokai
 * @Description 主窗口
 */
public class MainFrame extends JFrame {
    private Image iconUrl;
    private TrayIcon trayIcon;
    private JPopupMenu popup;
    private JDialog dialog;
    private final int w;
    private final int h;
    private String iconPath;

    public MainFrame(String title, int w, int h, Color color) {
        super(title);
        setMinimumSize(new Dimension(500, 500));
        this.w = w;
        this.h = h;
        getContentPane().setBackground(color);
    }

    public void initMyJFrame(String iconPath, PropertiesManager propertiesManager) {
        this.iconPath = iconPath;
        // 设置 JFrame的 icon
        this.iconUrl = Toolkit.getDefaultToolkit().getImage(iconPath);
        // 设置 ico图标
        this.setIconImage(this.iconUrl);
        // 根据屏幕定位
        localCenter();
        // 初始化 托盘上的菜单
        initTrayPopupMenu();
        // 初始化 trayIcon
        initTrayIcon();

        // 设置 窗口关闭事件，使其 进入托盘
        setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                if (SystemTray.isSupported()) {
                    minimizeToTray();
                } else {
                    System.out.println("不支持最小化到托盘");
                    System.exit(0);
                }
            }
        });
        MyMenBar menBar = new MyMenBar(this);
        menBar.initMenBar(propertiesManager);
        setJMenuBar(menBar);
    }

    /**
     * 根据屏幕，将窗口定位到屏幕中心
     */
    private void localCenter() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        // 计算x
        int x = (int) (screenSize.getWidth() / 2 - this.w / 2);
        int y = (int) (screenSize.getHeight() / 2 - this.h / 2);
        setBounds(x, y, this.w, this.h);
    }

    /**
     * 设置 系统托盘图标对象
     * 支持：托盘菜单等操作
     */
    private void initTrayIcon() {
        // 根据image、提示、菜单创建 TrayIcon【系统托盘图标类】
        this.trayIcon = new TrayIcon(this.iconUrl, "事项提醒");
        // 给TrayIcon添加 鼠标点击事件，单击直接显示窗口
        this.trayIcon.addMouseListener(new MouseInputAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.getButton() == 1) {
                    showJFrame();
                } else if (e.getButton() == 3 && e.isPopupTrigger()) {
                    showPopupMenu(e);
                }
            }
        });

        // 设置 托盘图标大小自动调整
        this.trayIcon.setImageAutoSize(true);
    }

    private void initTrayPopupMenu() {
        // 创建 JDialog 弹出窗口。利用 JPopupMenu 当show在某个组件上时，点击屏幕任意地方，会使JPopupMenu自动小时特性，完成菜单关闭
        // 由于只是一个辅助组件，不需要什么设置
        this.dialog = new JDialog();
        this.dialog.setSize(0, 0);
        // 设置为 没有 关闭按钮
        this.dialog.setUndecorated(true);

        // 创建 弹出菜单，并重写 即将隐藏方法。
        this.popup = new JPopupMenu() {
            @Override
            protected void firePopupMenuWillBecomeInvisible() {
                // 将 dialog也设置为 不可见
                dialog.setVisible(false);
            }
        };
        JMenuItem showItem = new JMenuItem("打开事项提醒");
        showItem.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                super.mouseMoved(e);
            }
        });
        showItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showJFrame();
            }
        });
        JMenuItem exitItem = new JMenuItem("退出");
        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        JMenuItem rebootItem = new JMenuItem("重启");
        rebootItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("重启 -> " + reBoot());
            }
        });

        // 将item添加到菜单
        this.popup.add(showItem);
        this.popup.add(rebootItem);
        this.popup.add(exitItem);
    }

    /**
     * 获取 桌面的系统托盘
     */
    public void minimizeToTray() {
        setVisible(false);
        // 初始化 系统托盘
        SystemTray tray = SystemTray.getSystemTray();
        try {
            TrayIcon[] trayIcons = tray.getTrayIcons();
            // 如何托盘中，存在JFrame的trayIcon对象，则不再添加
            if (trayIcons.length == 0) {
                tray.add(this.trayIcon);
            }
        } catch (AWTException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 显示 JFrame
     */
    public void showJFrame() {
        // 菜单不可见
        this.popup.setVisible(false);
        // JFrame 设置可见
        this.setVisible(true);
        // 设置 Frame状态
        this.setExtendedState(Frame.NORMAL);
        // 将JFrame从托盘中移除
        // SystemTray.getSystemTray().remove(trayIcon);
    }

    /**
     * 处理 PopupMenu 菜单
     * 利用 菜单在 组件上 show 显示时，点击屏幕其他地方，会自动隐藏菜单特性，完成 当 打开菜单后，点击其他地方，自动关闭菜单
     */
    private void showPopupMenu(AWTEvent e) {
        if (e instanceof MouseEvent) {
            MouseEvent me = (MouseEvent) e;
            // 先获取鼠标坐标
            int x = me.getX() + 10;
            int y = me.getY() - this.popup.getHeight();
            this.dialog.setLocation(x, y);
            this.dialog.setVisible(true);
            this.popup.show(this.dialog, 0, 0);
        }
    }

    /**
     * java 调用vbs脚本，重启程序
     */
    public String reBoot() {
        File file = new File(this.iconPath);
        String parent = file.getParent();
        String vbsFile = parent.substring(0, parent.lastIndexOf("\\")) + "\\start.vbs";
        try {
            Runtime.getRuntime().exec("cscript " + vbsFile);
            return "重启成功";
        } catch (NullPointerException | IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}